<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        display: flex;
      }
      div {
        margin: auto;
        margin-top: 30px;
      }
      td {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div>
      <input type="text" name="" id="username" />
      <input type="text" name="" id="age" />
      <input type="text" name="" id="sex" />
      <button id="add">添加</button>
      <table border="1" style="width: 600px; margin-top: 20px">
        <thead>
          <tr>
            <td colspan="4" style="text-align: center">学生信息表</td>
          </tr>
          <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
  </body>
  <script>
    window.onload = function () {
      document.getElementById('add').addEventListener('click', addFun)
    }
    function delFun(obj) {
      var tbodyObj = obj.parentNode.parentNode.parentNode
      var trObj = obj.parentNode.parentNode
      tbodyObj.removeChild(obj.parentNode.parentNode)
    }
    function addFun() {
      var username = document.getElementById('username').value,
        age = document.getElementById('age').value,
        sex = document.getElementById('sex').value
      var trObj = document.createElement('tr'),
        tdObj1 = document.createElement('td'),
        tdObj2 = document.createElement('td'),
        tdObj3 = document.createElement('td'),
        tdObj4 = document.createElement('td')
      tdObj1.innerHTML = username
      tdObj2.innerHTML = age
      tdObj3.innerHTML = sex
      tdObj4.innerHTML = '<a href="#" onclick="delFun(this)">删除</a>'
      trObj.appendChild(tdObj1)
      trObj.appendChild(tdObj2)
      trObj.appendChild(tdObj3)
      trObj.appendChild(tdObj4)
      var tbodyObj = document.getElementsByTagName('tbody')[0]
      tbodyObj.insertBefore(trObj, tbodyObj.firstChild)
    }
  </script>
</html>
